// Web Worker for highlighting MDB content
self.onmessage = function(e) {
  if (e.data.type === 'highlight') {
    const { content, searchTerm } = e.data
    
    try {
      const result = processHighlight(content, searchTerm)
      self.postMessage({
        type: 'highlight',
        result: result
      })
    } catch (error) {
      self.postMessage({
        type: 'error',
        error: error.message
      })
    }
  }
}

function processHighlight(content, searchTerm) {
  if (!content || !searchTerm) {
    return content || ''
  }
  
  // 转义 HTML 特殊字符
  const escapeHtml = (text) => {
    return text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
  }
  
  const escapedContent = escapeHtml(content)
  const escapedSearchTerm = escapeHtml(searchTerm)
  
  // 创建正则表达式，不区分大小写
  const regex = new RegExp(`(${escapedSearchTerm})`, 'gi')
  
  // 替换匹配项为高亮标记
  return escapedContent.replace(regex, '<mark class="search-highlight">$1</mark>')
} 